import { ReactNode, useEffect } from "react";
import { ItemSpin } from "./Spin";
import { Empty, Spin } from "antd";

export type InfiniteScrollLoading = "reload" | "loadmore" | false;

/**
 * 先决条件
 * 初始列表的总高度就一定要大于InfiniteScroll组件的height属性值
 */
const InfiniteScroll: React.FC<{
  next: (init?: boolean) => Promise<void>;
  hasMore: boolean;
  loading: InfiniteScrollLoading;
  children?: ReactNode;
  total?: number;
  /** 距离底部的阀值*/
  threshold?: number;
}> = (p) => {
  const { loading, next, hasMore, children, threshold = 20, total = -1 } = p;

  const handleScroll = () => {
    if (!hasMore || loading) return;

    //窗口高度
    const windowHeight = window.innerHeight;

    //内容高度包括滚动条
    const documentHeight = Math.max(
      document.body.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.scrollHeight,
      document.documentElement.offsetHeight
    );

    const windowBottom = windowHeight + window.scrollY + threshold;
    if (windowBottom >= documentHeight) {
      next();
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [hasMore, loading]);

  return (
    <>
      <Spin spinning={loading === "reload"}>
        <div className="min-h-[40px]">
          {total === 0 ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="没有内容"
            />
          ) : (
            children
          )}
        </div>
      </Spin>
      {loading === "loadmore" && <ItemSpin />}
    </>
  );
};

export default InfiniteScroll;
